import 'dart:math';
import 'package:flutter/material.dart';
import '../../../common/style/extension_util.dart';
import 'package:get/get.dart';

import '../style/app_style.dart';

class ProcessBarView extends StatefulWidget {
  final void Function(double start, double end,double sclae)? onChange;
  ///必传 不然不准
  final double maxWidth;
  final List<double>? points;
  final double startValue;
  final double? startMaxValue;
  final double endValue;
  final double? endMinValue;
  final double scaleMax;
  final double? minToZero;
  final bool onlyEnd;
  final Color? endColor;
  final Color? startColor;
  final Color? smallColor;
  final double? ballSize;
  final double? smallSize;

  /// 进度区分
  final bool? processDiff;
  const ProcessBarView(
      {super.key,
      required this.onChange,
      this.startValue = 0.0,
      this.endValue = 1.0,
      this.maxWidth = 200,
      this.scaleMax = 1.0,
      this.points, this.minToZero = 1,
        this.startMaxValue = 0.5,
        this.endMinValue = 0.5,
        this.onlyEnd = false,
        this.startColor,
        this.endColor,
        this.smallColor,
        this.ballSize,
        this.smallSize,
        this.processDiff = false
      });

  @override
  State<ProcessBarView> createState() => ProcessBarViewState();
}

class ProcessBarViewState extends State<ProcessBarView>
    with SingleTickerProviderStateMixin {
  late List<double> _points;
  double _smallBallWidth = 12;
  double _ballWidth = 18;
  double _scaleSpace = 300;
  double _startValue = 0;
  double _endValue = 1;

  Offset _dragOffset = Offset.zero;
  Offset _endOffset = Offset.zero;
  double _scale = 0.1;

  double _starMaxValue = 1,_endMinValue = 0,_originStartMax = 1;
  double _topSpace = 0.0 ,_topSmallSpace = 0.0;
  double _maxWidth = 0.0;


  @override
  void initState() {
    _maxWidth = widget.maxWidth;
    setDefaultArg();
    super.initState();
  }

  setDefaultArg(){
    if(widget.ballSize != null){
      _ballWidth = widget.ballSize!;
    }
    _ballWidth = 60;
    if(widget.smallSize != null){
      _smallBallWidth = widget.smallSize!;
    }

    _points = widget.points ?? [0.5];
    ///这个是差值最大值减最小值
    if(widget.scaleMax != 1){
      var scale = 1.0 /  widget.scaleMax;
      _scale = scale;
      _startValue = (widget.startValue - (widget.minToZero ?? 1))  * scale;
      _endValue = scale * (widget.endValue - (widget.minToZero ?? 1));

      if(widget.startMaxValue != null) {
        _starMaxValue = (widget.startMaxValue!  - (widget.minToZero ?? 1) )/ widget.scaleMax ;
        _originStartMax = _starMaxValue;
      }
      if(widget.endMinValue != null) {
        _endMinValue = (widget.endMinValue! - (widget.minToZero ?? 1)) / widget.scaleMax;
      }
    }else{
      _startValue = widget.startValue;
      _endValue = widget.endValue;
    }
    _scaleSpace = _maxWidth - _ballWidth;
    _dragOffset = Offset(_startValue * _scaleSpace  , 0);
    _endOffset = Offset(_endValue * _scaleSpace , 0);
  }

  updateValues(double startValue,double endValue){
    if(widget.scaleMax != 1){
      var scale = 1.0 /  widget.scaleMax;
      _scale = scale;
      _startValue = (startValue- (widget.minToZero ?? 1))  * scale;
      _endValue = scale * (endValue - (widget.minToZero ?? 1));

      if(widget.startMaxValue != null) {
        _starMaxValue = (widget.startMaxValue!  - (widget.minToZero ?? 1) )/ widget.scaleMax ;
        _originStartMax = _starMaxValue;
      }
      if(widget.endMinValue != null) {
        _endMinValue = (widget.endMinValue! - (widget.minToZero ?? 1)) / widget.scaleMax;
      }
    }else{
      _startValue = startValue;
      _endValue = endValue;
    }
    _dragOffset = Offset(_startValue * _scaleSpace  , 0);
    _endOffset = Offset(_endValue * _scaleSpace , 0);
    setState(() {

    });
  }

  _scalePositionLeft(double e) {
    var space = 0.5;

    var isBig = _points.firstWhereOrNull((element) => element > 1);
    if(isBig == null){
      space = max(e * (_maxWidth - _smallBallWidth), 0.0);
    }else{
      space = (e - (widget.minToZero ?? 1))  * _scale * (_maxWidth - _smallBallWidth);
    }
    return Positioned(
        left: space,
        top: _topSmallSpace,
        child: Container(
          width: _smallBallWidth,
          height: _smallBallWidth,
          decoration: BoxDecoration(
              color: widget.smallColor ?? AppColor.backGroundColor,
              borderRadius: BorderRadius.circular(_smallBallWidth / 2)),
        ));
  }


  _scrollBall(double e, int index) {
    if (e >= 1.0) {
      e = 1.0;
    }
    // var space = max(e * _scaleSpace , 0.0);
    var space = index == 0 ? _dragOffset.dx : _endOffset.dx;
    return Positioned(
        left: space,
        top: _topSpace,
        child: GestureDetector(
            onPanUpdate: (DragUpdateDetails details) {
              if (index == 0) {
                var newDetail = Offset(
                  _dragOffset.dx + details.delta.dx,
                  _dragOffset.dy + details.delta.dy,
                );

                var scale  = newDetail.dx / (_scaleSpace );
                if(widget.onlyEnd == false) {
                  if (scale / _scale > _endValue / _scale - 1) {
                    return;
                  }
                }
                if(scale > _starMaxValue ){
                  return;
                }

                if(newDetail.dx <= 0){
                  scale = 0;
                  _dragOffset = Offset(0,details.delta.dy);
                }else if(newDetail.dx >= _scaleSpace ) {
                  scale = 1;
                  _dragOffset = Offset(_scaleSpace ,details.delta.dy);
                }else{
                  scale = newDetail.dx / (_scaleSpace );
                  _dragOffset = newDetail;
                  // print("startScale = $scale _max == $_starMaxValue");
                }
                _startValue = scale;
              } else {
                var newDetail = Offset(
                  _endOffset.dx + details.delta.dx,
                  _endOffset.dy + details.delta.dy,
                );

                var scale  = newDetail.dx / (_scaleSpace );
                // print("endScale = $scale _endMin == $_endMinValue");
                if(widget.onlyEnd == false) {
                  if (scale / _scale < _startValue / _scale + 1) {
                    return;
                  }
                }
                if(scale < _endMinValue ){
                  return;
                }
                if(newDetail.dx <= 0){
                  scale = 0;
                  _endOffset = Offset(0,details.delta.dy);
                }else if(newDetail.dx >= _scaleSpace) {
                  scale = 1;
                  _endOffset = Offset(_scaleSpace,details.delta.dy);
                }else{
                  scale = newDetail.dx / (_scaleSpace );
                  _endOffset = newDetail;
                }
                _endValue = scale;
              }
              setState(() {});
              widget.onChange?.call(_startValue / _scale + (widget.minToZero ?? 1.0), _endValue / _scale + (widget.minToZero ?? 1.0),_scale);
            },
            onPanEnd: (details){
              // setNormalBoundary();
            },
            behavior: HitTestBehavior.opaque,
            child: Container(
              // color: Colors.purple,
              width: _ballWidth,
              height: _ballWidth,
              alignment: Alignment(2 * e - 1,0),
              child: SizedBox(width: widget.ballSize ?? (18) ,height:widget.ballSize ?? (18),)
                  .addContainer(color: index == 0 ? widget.startColor ?? Colors.red : widget.endColor ?? Colors.orange,
              radius: (widget.ballSize ??(18)) / 2.0),
            )));
  }

  bool onlyOneCalculate = false;
  @override
  Widget build(BuildContext context) {
    Widget getPosition(e) {
      return _scalePositionLeft(e);
    }
    return LayoutBuilder(builder: (context,constraints){
        if(constraints.maxWidth > _maxWidth && onlyOneCalculate == false){
          onlyOneCalculate = true;
          _maxWidth = constraints.maxWidth;
          setDefaultArg();
        }
      _topSpace = (constraints.maxHeight - _ballWidth) / 2.0;
      _topSmallSpace = (constraints.maxHeight - _smallBallWidth) / 2.0;

      var smallBall = _points.map((e) => getPosition(e)).toList();
      List<Widget> children = [];
      children.add(Align(
          child: Container(
            height: (8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              color: widget.smallColor ?? AppColor.backGroundColor,
            ),
          )));
      if(widget.processDiff == true){
        print("endvalue ==== ${_endValue}");
        children.add(Align(alignment: Alignment.centerLeft,child: Container(height: 8,width: _endValue * (_scaleSpace  + _ballWidth),  decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4), color: widget.endColor
        )),));
      }
      children.addAll(smallBall);
      if(widget.onlyEnd == false) {
        children.add(_scrollBall(_startValue, 0));
      }
      children.add(_scrollBall(_endValue, 1));
      // return ResizePage(builder: () {
        return Stack(
          children: children,
        ).addContainer(width: _maxWidth, color: Colors.transparent);
      // });
    });

  }
}

